package com.totoro.agent;

import java.lang.instrument.Instrumentation;

/**
 * 动态定义
 * 主要为了获取Instrumentation对象，用来从新定义class
 * Created by Niki on 2018/4/10 19:49
 */
public class JavaDynAgent {
    private static Instrumentation instrumentation;
    private static Object lockObject = new Object();

    public JavaDynAgent() {
    }

    public static void agentmain(String args, Instrumentation ins) {
        synchronized (lockObject) {
            if (JavaDynAgent.instrumentation == null) {
                JavaDynAgent.instrumentation = ins;
                System.out.println(">>>>java agent 代理：init instrumentation");
                System.out.println(instrumentation == null ? ">>>>null" : ">>>>" + instrumentation.toString());
            } else {
                System.out.println(">>>>instrumentation is inited");
            }
            System.out.println(JavaDynAgent.class.getClassLoader());
        }
    }

    public static Instrumentation getInstrumentation() {
        return JavaDynAgent.instrumentation;
    }

    public static long sizeOf(Object object) {
        return instrumentation.getObjectSize(object);
    }
}
